import os
import dashscope
from datetime import datetime
from typing import List, Dict


def generate_travel_guide(api_key: str,
                          base_info: Dict,
                          preferences: Dict,
                          resources: Dict,
                          selected_interests: List[str],
                          existing_interests: List[str] = None) -> str:
    """
    Generates travel guides using the official Dashscope SDK

    Parameters:
    api_key - Qwen API key
    base_info - Dictionary containing basic information
    preferences - Dictionary containing preference requirements
    resources - Dictionary containing resource configurations
    selected_interests - User's selected interest tags for this request
    existing_interests - User's historical interest tags (optional)
    """
    # Merge interest tags
    all_interests = list(set((existing_interests or []) + selected_interests))

    # Construct system prompt
    system_prompt = """You are a professional travel planner. Please generate a well-structured travel guide based on the following requirements:
1. Use Markdown format
2. Include daily schedules
3. Provide practical advice and precautions
4. Align with specified budget and travel style"""

    # Construct user input
    user_input = f"""
【Destination】{base_info['destination']}

【Schedule】
- Departure: {base_info['departure_date'].strftime('%B %Y')}
- Duration: {base_info['duration']}

【Group Composition】{base_info['group_description']}

【Interests】{", ".join(all_interests)}

【Travel Style】{preferences['style']}

【Special Requirements】{preferences['restrictions'] or "None"}

【Budget】{resources['budget']}

【Accommodation】{resources['accommodation']}

【Transportation】{resources['transportation']}
"""

    # Build messages list
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_input}
    ]

    try:
        response = dashscope.Generation.call(
            model="qwen-max",
            api_key=api_key,
            messages=messages,
            result_format='message',  # Return structured message
            temperature=0.7,  # Control creativity
            top_p=0.9,  # Control diversity
            seed=1234  # Fixed seed for reproducibility
        )

        if response.status_code == 200:
            return response.output.choices[0].message.content
        else:
            print(f"API call failed. Status code: {response.status_code}, Error: {response.message}")
            return None

    except Exception as e:
        print(f"Exception occurred: {str(e)}")
        return None


# Example usage
if __name__ == "__main__":
    # Configure API key (recommended via environment variable)
    API_KEY = os.getenv('DASHSCOPE_API_KEY')

    # Build test parameters
    test_params = {
        "base_info": {
            "destination": "Great Wall of China",
            "departure_date": datetime(2025, 5, 1),
            "duration": "3 days 2 nights",
            "group_description": "2 adults with 1 child aged 10"
        },
        "preferences": {
            "style": "Cultural immersion + family-friendly",
            "restrictions": "Requires midday break time"
        },
        "resources": {
            "budget": "Mid-range (1000 CNY per day)",
            "accommodation": "4-star hotel in Wangfujing area",
            "transportation": "Subway + ride-hailing"
        },
        "selected_interests": ["Imperial culture", "Ancient architecture"],
        "existing_interests": ["History", "Museums"]
    }

    # Generate guide
    guide = generate_travel_guide(
        api_key=API_KEY,
        **test_params
    )

    if guide:
        print("Successfully generated travel guide:\n")
        print(guide)
    else:
        print("Guide generation failed")